package com.itbaizhan.springsecuritydemo1;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itbaizhan.springsecuritydemo1.mapper.UserMapper;
import com.itbaizhan.springsecuritydemo1.pojo.Permission;
import com.itbaizhan.springsecuritydemo1.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //创建查询条件
        QueryWrapper<Users> wapper = new QueryWrapper<Users>().eq("username", username);
        //查询用户
        Users users = userMapper.selectOne(wapper);
        if (users!=null){
            return null;
        }
        
        //获取用户权限
        List<Permission> permissions = userMapper.findByPermission(username);
        //把集合转为security
        List<GrantedAuthority> grantedAuthorities = new ArrayList();
        //遍历permission  获取他的用户权限的资源
        for (Permission permission : permissions) {
            grantedAuthorities.add(new SimpleGrantedAuthority(permission.getUrl()));
        }
        UserDetails details = User.withUsername(users.getUsername()).
                password(users.getPassword()).
                authorities(grantedAuthorities).
                build();
        return details;
    }
}
